package com.longxi.tianjintianbao.ui.presenter.common;

import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;

import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.listener.SelectEnterEditTextListener;
import com.longxi.tianjintianbao.listener.SelectEnterStateListener;
import com.longxi.tianjintianbao.model.completeEnter.EnterEditText;
import com.longxi.tianjintianbao.model.completeEnter.EnterState;
import com.longxi.tianjintianbao.model.completeEnter.PicturesChoose;
import com.longxi.tianjintianbao.model.completeEnter.PicturesPath;
import com.longxi.tianjintianbao.ui.adapter.GridImageAdapter;
import com.longxi.tianjintianbao.ui.adapter.multitype.LabelViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.completeEnter.EnterEditTextViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.completeEnter.EnterStateViewBinder;
import com.longxi.tianjintianbao.ui.adapter.multitype.completeEnter.PicturesChooseViewBinder;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.view.common.ICompleteEnterAtView;
import com.longxi.tianjintianbao.utils.LogUtils;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

import static com.luck.picture.lib.config.PictureMimeType.ofImage;

public class CompleteEnterAtPresenter extends BasePresenter<ICompleteEnterAtView> {
    public static String TITLE = "TITLE";

    public static String ENTER_EDITTEXT = "ENTER_EDITTEXT";
    public static String ENTER_STATE_LIST = "ENTER_STATE_LIST";

    public static String ENTEREDITTEXT = "ENTEREDITTEXT";
    public static String SELECTSTATE = "SELECTSTATE";
    public static String SELECTPIC = "SELECTPIC";

    private MultiTypeAdapter adapter;
    private Items items;
    int SPAN_COUNT = 4;
    List<EnterState> enterStateList = new ArrayList<>();
    private String enterEditText = "";
    private String selectState = "1";

    private List<LocalMedia> selectList = new ArrayList<>();
    private List<PicturesPath> picturesPathList = new ArrayList<>();
    private GridImageAdapter gridImageAdapter;

    public CompleteEnterAtPresenter(BaseActivity context) {
        super(context);
    }

    public void initAdapter(){
        if(adapter == null){
            adapter = new MultiTypeAdapter();
            /* 注册类型和 View 的对应关系 */
            SelectEnterEditTextListener selectEnterEditTextListener = new SelectEnterEditTextListener() {
                @Override
                public void onSuccess(EnterEditText enterEditText) {
                    getEnterEditText(enterEditText.getValue());
                }
            };
            adapter.register(EnterEditText.class, new EnterEditTextViewBinder(selectEnterEditTextListener));

            gridImageAdapter = new GridImageAdapter(mContext, onAddPicClickListener);
            adapter.register(PicturesChoose.class, new PicturesChooseViewBinder(mContext, selectList, gridImageAdapter));
            adapter.register(String.class, new LabelViewBinder());
            SelectEnterStateListener selectEnterStateListener = new SelectEnterStateListener() {
                @Override
                public void onSuccess(EnterState enterState) {
                    singleElection(enterState);
                }
            };
            adapter.register(EnterState.class, new EnterStateViewBinder(selectEnterStateListener));
            final GridLayoutManager layoutManager = new GridLayoutManager(mContext, SPAN_COUNT);
            GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {
                    Object item = items.get(position);
                    if (item instanceof EnterEditText) {
                        return SPAN_COUNT;
                    }
                    if (item instanceof String) {
                        return SPAN_COUNT;
                    }
                    if (item instanceof EnterState) {
                        return 1;
                    }
                    return SPAN_COUNT;
                }
            };
            layoutManager.setSpanSizeLookup(spanSizeLookup);
            getView().getRvContent().setLayoutManager(layoutManager);
            getView().getRvContent().setAdapter(adapter);
        }
    }

    public void setUi(){
        Intent intent = mContext.getIntent();

        mContext.setTitle(intent.getStringExtra(TITLE));
        mContext.setTvLeft(MyUtils.getString(R.string.back));
        mContext.setTvRight("保存");

        EnterEditText enterEditText = (EnterEditText) intent.getSerializableExtra(ENTER_EDITTEXT);
        enterStateList = (List<EnterState>) intent.getSerializableExtra(ENTER_STATE_LIST);


        items = new Items();
        if(enterEditText != null){
            items.add(enterEditText);
        }

        items.add(new PicturesChoose());

        if(enterStateList != null && enterStateList.size() > 0){
            items.add("设备状态");
            items.addAll(enterStateList);
        }

        adapter.setItems(items);
        adapter.notifyDataSetChanged();
        mContext.hideLoading();
    }

    private boolean isNoSelect = false;

    /**
     * 获取输入内容
     * @param value
     */
    private void getEnterEditText(String value) {
        enterEditText = value;
    }

    /**
     * 获取单选内容
     * @param enterState
     */
    public void singleElection(EnterState enterState){
        for (int i = 0; i < enterStateList.size(); i++) {
            EnterState per = enterStateList.get(i);
            if(enterState.getStateValue().equals(per.getStateValue())){
                if(isNoSelect){
                    if(per.isSelect()){
                        per.setSelect(false);
                        selectState = "";
                    }else{
                        per.setSelect(true);
                        selectState = enterState.getStateValue();
                    }
                }else{
                    per.setSelect(true);
                    selectState = enterState.getStateValue();
                }
            }else{
                per.setSelect(false);
            }
        }

        //刷新切换状态栏
        for (int i = 0; i < items.size(); i++) {
            if (items.get(i) instanceof EnterState) {
                adapter.notifyItemChanged(i);
            }
        }
    }

    /**
     * 点击保存 有没有值先不判断
     */
    public void onClickSaveBtn(){
        Intent intent = mContext.getIntent();
        intent.putExtra(ENTEREDITTEXT, enterEditText);
        intent.putExtra(SELECTSTATE, selectState);
        intent.putExtra(SELECTPIC, (Serializable) picturesPathList);
        mContext.setResult(mContext.RESULT_OK, intent);
        mContext.finish();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                selectList = PictureSelector.obtainMultipleResult(data);
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                picturesPathList.clear();
                for (LocalMedia media : selectList) {
                    LogUtils.i("图片-----》", media.getPath());
                    picturesPathList.add(new PicturesPath(media.getCompressPath()));
                }
                gridImageAdapter.setList(selectList);
                gridImageAdapter.notifyDataSetChanged();
                break;
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            boolean mode = true;
            if (mode) {
                // 进入相册 以下是例子：不需要的api可以不写
                PictureSelector.create(mContext)
                        .openGallery(ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                        .maxSelectNum(2)// 最大图片选择数量
                        .minSelectNum(1)// 最小选择数量
                        .imageSpanCount(4)// 每行显示个数
                        .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                        .previewImage(true)// 是否可预览图片
                        .isCamera(true)// 是否显示拍照按钮
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        //.setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
                        .enableCrop(false)// 是否裁剪
                        .compress(true)// 是否压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
                        //.compressSavePath(getPath())//压缩图片保存地址
                        //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                        .withAspectRatio(16, 9)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                        .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示
                        .isGif(false)// 是否显示gif图片
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                        .circleDimmedLayer(false)// 是否圆形裁剪
                        .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                        .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                        .openClickSound(false)// 是否开启点击声音
                        .selectionMedia(selectList)// 是否传入已选图片
                        //.isDragFrame(false)// 是否可拖动裁剪框(固定)
//                        .videoMaxSecond(15)
//                        .videoMinSecond(10)
                        //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
                        //.cropCompressQuality(90)// 裁剪压缩质量 默认100
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
                        //.rotateEnabled(true) // 裁剪是否可旋转图片
                        //.scaleEnabled(true)// 裁剪是否可放大缩小图片
                        //.videoQuality()// 视频录制质量 0 or 1
                        //.videoSecond()//显示多少秒以内的视频or音频也可适用
                        //.recordVideoSecond()//录制视频秒数 默认60s
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
            }
        }

        @Override
        public void onDeletePic(LocalMedia localMedia) {

        }

        @Override
        public void onPreview(int position) {
            PictureSelector.create(mContext).themeStyle(R.style.picture_default_style).openExternalPreview(position, selectList);
        }
    };

}
